import { readFileAsDataURL, dataUrlToImage } from "@/lib/utils";
import { defaultRowsAndCols } from "./constant";

const cellSize = 12;

/**
 * Recognizes pixel points in an image file.
 * @param {File} file - The image file to process.
 * @returns {Promise<Array>} - Promise resolving to an array of recognized pixel points.
 */
export const recognizePixels = async (file) => {
  if (!file) {
    throw new Error("No file provided");
  }

  const dataUrl = await readFileAsDataURL(file);
  const image = await dataUrlToImage(dataUrl);

  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");

  canvas.width = defaultRowsAndCols.cols * cellSize;
  canvas.height = defaultRowsAndCols.rows * cellSize;

  context.drawImage(
    image,
    0,
    0,
    image.width,
    image.height,
    0,
    0,
    canvas.width,
    canvas.height
  );

  const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  const pixels = imageData.data;

  const points = [...new Array(pixels.length / 4)].map((_, i) =>
    pixels[i * 4 + 3] === 0 ? false : true
  );

  const recognizedPoints = [];

  for (let row = 0; row < defaultRowsAndCols.rows; row += 1) {
    const recognizedPoint = [];
    for (let col = 0; col < defaultRowsAndCols.cols; col += 1) {
      const x = col * cellSize;
      const y = row * cellSize;
      const width = cellSize;
      const height = cellSize;

      // 在 points 获取这个区域（x,y,width,height）的points 数据
      const regionPoints = [];
      for (let i = y; i < y + height; i++) {
        for (let j = x; j < x + width; j++) {
          const index = i * canvas.width + j;
          regionPoints.push(points[index]);
        }
      }

      recognizedPoint.push(
        regionPoints.filter(Boolean).length / regionPoints.length > 0.8 ? 1 : 0
      );
    }
    recognizedPoints.push(recognizedPoint);
  }

  return recognizedPoints;
};
